package com.liu.voluntary.handler;

import com.liu.voluntary.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    //目标方法执行前被调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        log.info("拦截到请求：{} {}", method, requestURI);

        // 如果是登录相关的POST请求，直接放行
        if ("POST".equals(method) && (requestURI.equals("/toUser") || requestURI.equals("/toAdmin"))) {
            return true;
        }

        // 检查Cookie中的登录凭证
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("Ticket".equals(cookie.getName())) {
                    String ticket = cookie.getValue();
                    if (ticket != null && !ticket.isEmpty()) {
                        Object attribute = request.getSession().getAttribute(ticket);
                        if (attribute == null){
                            log.info("用户未登录，重定向到登录页面");
                            request.setAttribute("msg", "请先登录");
                            response.sendRedirect("/toLoginPage");
                            return false;
                        }
                        return true;
                    }
                }
            }
        }

        log.info("用户未登录，重定向到登录页面");
        request.setAttribute("msg", "请先登录");
        response.sendRedirect("/toLoginPage");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle 执行了");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion 执行了");
    }
}
